<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '订单列表',
  },
}
</route>

<template>
  <!-- 选项卡容器 -->
  <wd-sticky :offset-top="0">
    <view class="tab-container">
      <view
        v-for="(tab, index) in tabs"
        :key="index"
        :class="['tab-item', queryParams.type === tab.value ? 'active' : '']"
        @click="handleTabChange(tab.value)"
      >
        {{ tab.label }}
      </view>
    </view>
  </wd-sticky>

  <!-- 滚动容器 -->
  <scroll-view
    class="order-scroll"
    scroll-y
    :refresher-enabled="true"
    :style="{ height: scrollHeight + 'px' }"
    :refresher-triggered="isRefreshing"
    refresher-background="#f5f5f5"
    refresher-default-style="none"
    :refresher-threshold="0"
    @refresherrefresh="handlerRefresh"
    @scrolltolower="onReachBottom"
  >
    <CustomRefresh
      :is-refreshing="isRefreshing"
      :error="refreshError"
      :last-refresh-time="lastRefreshTime"
    />

    <!-- 订单列表 -->
    <view class="order-list">
      <view v-for="(order, index) in orderList" :key="order.orderNo" class="order-item">
        <!-- 订单头部 -->
        <view class="order-header">
          <text class="order-no">订单号：{{ order.orderNo }}</text>
          <text class="order-status">{{ OrderStatusMap[order.orderStatus] }}</text>
        </view>

        <!-- 商品主体 -->
        <view class="order-main">
          <!-- 左侧商品信息 -->
          <view class="product-list">
            <view
              class="product-info"
              v-for="item in order.isShow ? order.orderItemList : order.orderItemList.slice(0, 1)"
              :key="item.id.toString"
              @click="navigateToDetail(order.id)"
            >
              <image :src="item.thumbImg" class="product-image" mode="aspectFill" />
              <view class="product-detail">
                <text class="product-name">{{ item.skuName }}</text>
                <text class="product-spec">*{{ order.goodsNum }}</text>
                <text class="product-price">¥{{ item.skuPrice }}</text>
              </view>
            </view>
          </view>

          <!-- 右侧统计信息 -->
          <view class="order-stats">
            <text class="total-amount">¥{{ order.totalAmount }}</text>
            <text class="product-count">共{{ order.goodsNum }}件</text>
            <text
              v-if="!order.isShow && orderList[index].orderItemList.length > 1"
              class="expand-btn"
              @click.stop="showAllItem(order.id)"
            >
              展开
            </text>
            <text
              v-if="order.isShow && orderList.length > 1"
              class="expand-btn"
              @click.stop="showAllItem(order.id)"
            >
              收起
            </text>
          </view>
        </view>
        <wd-divider class="order-divider"></wd-divider>
        <!-- 操作按钮组 -->
        <view class="action-buttons">
          <view
            class="btn cancel-btn"
            v-if="order.orderStatus === OrderStatusEnum.WAIT_PAY"
            @click.stop="closeOrder(order.id)"
          >
            取消订单
          </view>
          <view
            class="btn pay-btn"
            @click="goPay(order.orderNo)"
            v-if="order.orderStatus === OrderStatusEnum.WAIT_PAY"
          >
            去支付
          </view>
          <view
            class="btn pay-btn"
            v-if="
              order.orderStatus === OrderStatusEnum.CANCEL ||
              order.orderStatus === OrderStatusEnum.COMPLETED
            "
            @click="deleteOrder(order.id)"
          >
            删除订单
          </view>
          <view
            class="btn pay-btn"
            v-if="order.orderStatus === OrderStatusEnum.WAIT_COMMENT"
            @click="handelWaitComment(order.id)"
          >
            去评价
          </view>
          <view
            class="btn pay-btn"
            v-if="order.orderStatus === OrderStatusEnum.ALREADY_DELIVER"
            @click="confirmReceipt(order.id)"
          >
            确认收货
          </view>
          <!-- <view class="btn reorder-btn">再来一单</view> -->
        </view>
      </view>
    </view>
    <wd-loadmore :loading="loading" />
  </scroll-view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useMessage, useToast } from 'wot-design-uni'
import { OrderApi, OrderStatusMap } from '@/service/order/order'
import { PayApi } from '@/service/pay/pay'
import { OrderStatusEnum } from '@/service/order/orderEnum.d'
import { usePagination } from '@/hooks/usePagination'
import { OrderStatusDto } from '@/service/order/order.d'
import { createDebounceFunc } from '@/utils/index'
import { usePullToRefresh } from '@/hooks/usePullToRefresh'
const message = useMessage()
const toast = useToast()
const CustomRefresh = defineAsyncComponent(() => import('@/components/customRefresh/index.vue'))

onLoad((options) => {
  console.log(options)
  if (options.type) {
    queryParams.value.type = Number(options.type)
  }
})
onShow(() => {
  handleTabChange(queryParams.value.type)
})

const systemInfo = uni.getSystemInfoSync()
const scrollHeight = ref(systemInfo.windowHeight - 40) // 80是顶部选项卡高度

//https://vpcs.fanyu.com/personal/gxnun
const tabs = ref([
  { label: '全部', value: 0 },
  { label: '进行中', value: 1 },
  { label: '待评价', value: 2 },
  { label: '退款/售后', value: 3 },
])

const {
  list: orderList,
  loading,
  loadData,
  reset: resetPagination,
  params: queryParams,
} = usePagination({
  apiMethod: OrderApi.getPageList,
  initialParams: {
    // 初始查询参数
    type: 0,
    size: 10,
  },
})

const handleTabChange = (value: number) => {
  resetPagination()
  queryParams.value.type = value
  loadData()
}

const { isRefreshing, refreshError, lastRefreshTime, handleRefresh } = usePullToRefresh(loading)

const onReachBottom = () => {
  // 加载更多逻辑
  console.log('加载更多逻辑')
  loadData()
}

const navigateToDetail = (orderId: number) => {
  uni.navigateTo({
    url: `/pages/order/detail?orderId=${orderId}`,
  })
}
const showAllItem = (orderId: number) => {
  const targetIndex = orderList.value.findIndex((item) => item.id === orderId)
  if (targetIndex > -1) {
    const currentOrder = orderList.value[targetIndex]
    currentOrder.isShow = !currentOrder.isShow
    console.log(currentOrder.isShow)

    orderList.value.splice(targetIndex, 1, currentOrder)
  }
}
const closeOrder = (orderId: number) => {
  if (orderId <= 0) return toast.show('非法点击')
  message
    .confirm({
      msg: '确定要取消订单吗？',
      title: '温馨提示',
    })
    .then(() => {
      uni.navigateTo({ url: `/pages/order/cancelOrder?orderId=${orderId}` })
    })
    .catch(() => {})
}

const { execute: goPay } = createDebounceFunc(
  async (orderNo: string) => {
    console.log(orderNo)
    const res = await PayApi.aliPay(orderNo)
    document.querySelector('body').innerHTML = res as unknown as string
    document.forms[0].submit()
  },
  1000,
  { leading: true, trailing: false },
)
const deleteOrder = (orderId: number) => {
  if (orderId <= 0) return toast.show('非法点击')
  message
    .confirm({
      msg: '确定要删除订单吗？删除后无法恢复！',
      title: '温馨提示',
    })
    .then(() => {
      OrderApi.deleteOrder(orderId)
        .then((res) => {
          if (res.code === 200) {
            toast.show('删除成功')
            queryParams.value.current = 1
            loadData()
          }
        })
        .catch(() => {
          toast.show('删除失败')
        })
    })
    .catch(() => {})
}

const confirmReceipt = (orderId: number) => {
  if (orderId <= 0) return toast.show('非法点击')
  message
    .confirm({
      msg: '确定要收货吗？',
      title: '温馨提示',
    })
    .then(() => {
      const obj: OrderStatusDto = {
        orderId,
        status: OrderStatusEnum.WAIT_COMMENT,
      }
      OrderApi.updateOrderStatus(obj)
        .then((res) => {
          if (res.code === 200) {
            toast.show('收货成功')
            queryParams.value.current = 1
            loadData()
          }
        })
        .catch(() => {
          toast.show('收货失败')
        })
    })
    .catch(() => {})
}

const handelWaitComment = (orderId: number) => {
  uni.navigateTo({ url: `/pages/goods/comment/addComment?orderId=${orderId}&type='insert'` })
}

const handlerRefresh = async () => {
  queryParams.value.current = 1

  await handleRefresh(loadData)
}
</script>

<style lang="scss" scoped>
/* 选项卡样式 */
.tab-container {
  display: flex;
  width: 100vw;
  height: 80rpx;
  background-color: #f5f5f5;
  .tab-item {
    min-width: 110rpx;
    font-size: 28rpx;
    line-height: 88rpx;
    color: #666;
    text-align: center;
    &.active {
      position: relative;
      font-weight: 500;
      color: #333;
      &::after {
        position: absolute;
        bottom: 0;
        left: 50%;
        width: 60rpx;
        height: 4rpx;
        content: '';
        background: #000;
        transform: translateX(-50%);
      }
    }
  }
}
/* 订单项样式 */
.order-item {
  padding: 16rpx;
  margin: 20rpx 12rpx;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);

  .order-header {
    display: flex;
    justify-content: space-between;
    padding-bottom: 24rpx;
    border-bottom: 1rpx solid #eee;
    .order-no {
      font-size: 24rpx;
      color: #999;
    }
    .order-status {
      font-size: 24rpx;
      color: #f60;
    }
  }

  .order-main {
    display: flex;
    padding: 12rpx 0;
    .product-list {
      flex: 1;

      overflow: hidden;

      // 展开动画
      transition: max-height 0.3s ease;
      .product-info {
        display: flex;
        flex: 1;
        margin-bottom: 20rpx;
        &:last-child {
          margin-bottom: 0;
        }
        .product-image {
          width: 120rpx;
          height: 120rpx;
          border: 1rpx solid #f5f5f5;
          border-radius: 8rpx;
        }
        .product-detail {
          display: flex;
          flex-direction: column;
          margin-left: 24rpx;
          .product-name {
            font-size: 24rpx;
            color: #333;
          }
          .product-spec {
            margin: 8rpx 0;
            font-size: 22rpx;
            color: #999;
          }
          .product-price {
            font-size: 24rpx;
            color: #f60;
          }
        }
      }
      &.expanded {
        max-height: 1000rpx; // 足够大的高度容纳所有商品
      }
    }
    .order-stats {
      position: relative;
      width: 120rpx;
      padding-left: 32rpx;
      &::before {
        position: absolute;
        top: 50%;
        left: 0;
        width: 1rpx;
        height: 80rpx;
        content: '';
        background: #eee;
        transform: translateY(-50%);
      }
      .total-amount {
        display: block;
        font-size: 28rpx;
        font-weight: 500;
        color: #f60;
      }
      .product-count {
        margin: 16rpx 0;
        font-size: 24rpx;
        color: #999;
      }
      .expand-btn {
        display: flex;
        align-items: center;
        font-size: 24rpx;
        color: #666;
      }
    }
  }
  .order-divider {
    margin-bottom: 16rpx;
  }
  .action-buttons {
    display: flex;
    gap: 12rpx;
    justify-content: flex-end;
    .btn {
      padding: 8rpx 20rpx;
      font-size: 24rpx;
      border-radius: 40rpx;
      &.cancel-btn {
        color: #666;
        border: 1rpx solid #ccc;
      }
      &.pay-btn {
        color: #000;
        border: 1rpx solid #999;
      }
      &.reorder-btn {
        color: #333;
        background: #f5f5f5;
      }
    }
  }
}
</style>
